<template>
  <nav class="pagination is-centered" role="navigation" aria-label="pagination">
    <a class="pagination-previous" @click="prev" v-show="current!==1">上一页</a>
    <a class="pagination-next" @click="next" v-show="current!==pages">下一页</a>
    <ul class="pagination-list">
      <li>
        <span class="pagination-ellipsis" v-show="prevMore">…</span>
      </li>
      <li>
        <a
          class="pagination-link"
          :class="[current === pager ? 'is-current' : '']"
          v-for="pager in pagers"
          @click="go(pager)"
          :key="pager"
        >{{ pager }}</a>
      </li>
      <li>
        <span class="pagination-ellipsis" v-show="nextMore">…</span>
      </li>
    </ul>
  </nav>
</template>

<script>
export default {
  props: {
    //页面中的可见页码，其他的以...替代, 必须是奇数
    perPages: {
      type: Number,
      default: 5
    },
    //当前页码
    current: {
      type: Number,
      default: 1
    },
    //每页显示条数
    pageSize: {
      type: Number,
      default: 10
    },
    //总记录数
    total: {
      type: Number,
      default: 1
    }
  },
  computed: {
    //计算总页码
    pages() {
      return Math.ceil(this.total / this.pageSize);
    },

    //计算页码，当count等变化时自动计算
    pagers() {
      const array = [];
      const _offset = (this.perPages - 1) / 2;

      const offset = {
        start: this.current - _offset,
        end: this.current + _offset
      };

      //-1, 3
      if (offset.start < 1) {
        offset.end = offset.end + (1 - offset.start);
        offset.start = 1;
      }
      if (offset.end > this.pages) {
        offset.start = offset.start - (offset.end - this.pages);
        offset.end = this.pages;
      }
      if (offset.start < 1) offset.start = 1;

      for (let i = offset.start; i <= offset.end; i++) {
        array.push(i);
      }

      return array;
    },
    prevMore() {
      return this.pagers[0] > 1;
    },
    nextMore() {
      return this.pagers[this.pagers.length - 1] < this.pages;
    }
  },
  methods: {
    prev() {
      if (this.current > 1) {
        this.go(this.current - 1);
      }
    },
    next() {
      if (this.current < this.pages) {
        this.go(this.current + 1);
      }
    },
    go(page) {
      if (this.current !== page) {
        this.$emit("change", page);
      }
    }
  }
};
</script>

